<?php


namespace App\Activity\Service\Free;


use App\Activity\Job\FreeOrderJob;
use App\Common\Service\BaseService;
use App\Activity\Repository\RepositoryFactory;
use App\Order\Model\OrderModel;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Support\Collection;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
use App\Common\Service\MiniAppService;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Di\Annotation\Inject;

class FreeBaseService extends BaseService
{
    /**
     * 公共字段集合
     */
    const GOODSFIELD=['scant_id','ratio','wx_crm_code', 'kz_goods_id', 'kz_type_id', 'cate_id', 'crd_cate_id', 'lsy_goods_name', 'lsy_unit_name', 'lsy_class_name'];
    const ACTIVITYFIELD=['activityID','activityType','begin_date','end_date','create_at','is_deleted','status','sort','shop_ids','title','status','activity_prams','is_view','image','updated_at','updated_uid'];
    const ACTIVITYGOODSFIELD=['id as activity_goods_id','activityID', 'goods_id as id', 'goods_cate','goods_title as title', 'goods_logo as logo','goods_spec','costprice as activity_price_market','price_selling as activity_price_selling','stock as activity_number_stock','spell_num','group_id','activityType','commission','need_invited_num','current_cost_price','per_can_buy_num','click_num','mini_app_code'];
    const GOODSLISTFIELD=['goods_pick_time'];
    const ACTIVITY_TYPE=5;

    /**
     * 删除状态 0未删除，1已删除
     */
    const ACTIVITY_IS_DELETED_0 = 0;
    const ACTIVITY_IS_DELETED_1 = 1;
    /**
     * 活动状态 0禁用，1启用
     */
    const ACTIVITY_STATUS_0 = 0;
    const ACTIVITY_STATUS_1 = 1;

    /**
     * @Inject()
     * @var MiniAppService
     */
    protected MiniAppService $miniAppService;
    /**
     * Repository
     */
    private $activity;
    private $activitygoods;

    /**
     * QuotaBaseService constructor.
     * @param RepositoryFactory $repositoryFactory
     */
    public function __construct(RepositoryFactory $repositoryFactory)
    {
        parent::__construct();
        $this->activity = $repositoryFactory->getRepository("activity");
        $this->activitygoods = $repositoryFactory->getRepository("activityGoods");
    }

    /**
     * 业务场景 获取限时抢购活动单条记录公共服务
     * @param array $needExceptKey
     * @param array $extraCondition
     * @param array $orderBy
     * @return array|mixed
     * @author ran
     * @date 2021-03-23 17:23
     * mailbox 466180170@qq.com
     */
    public function getFreeActivityCommonGoodsfirst(array $needExceptKey=[],array $extraCondition=[],array $orderBy=[]):array
    {
        $where =['store_activity_goods.activityType'=>self::ACTIVITY_TYPE];
        $condition=['where'=>array_merge($where,$extraCondition['where']??[]),'whereRaw'=>$extraCondition['whereRaw']??[],'whereOp'=>$extraCondition['whereOp']??[]];
        $activityArr =$this->activitygoods->findSonMoreUnionFirst(self::ACTIVITYGOODSFIELD,self::GOODSLISTFIELD,self::GOODSFIELD,$condition,$orderBy);
        return $this->arr->exceptArrKey($activityArr,$needExceptKey);
    }

    /**
     * 业务场景根据活动商品ID获取活动信息
     * @param array $needExceptKey
     * @param array $extraCondition
     * @param array $orderBy
     * @return array|mixed
     * @author ran
     * @date 2021-03-23 17:23
     * mailbox 466180170@qq.com
     */
    public function getFreeActivityInfoCommonfirstById(array $needExceptKey=[],array $extraCondition=[],array $orderBy=[]):array
    {
        $where =['store_activity_goods.activityType'=>self::ACTIVITY_TYPE];
        $condition=['where'=>array_merge($where,$extraCondition['where']??[]),'whereRaw'=>$extraCondition['whereRaw']??[],'whereOp'=>$extraCondition['whereOp']??[]];
        $activityArr =$this->activitygoods->findSonUnionFirst(self::ACTIVITYGOODSFIELD,self::ACTIVITYFIELD,$condition,$orderBy);
        return $this->arr->exceptArrKey($activityArr,$needExceptKey);
    }

    /**
     * @param string $openid
     * @param string $template_id
     * @param string $page
     * @param array $data
     * @return array|Collection|object|ResponseInterface|string
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws GuzzleException
     * @author ran
     * @date 2021-03-31 10:58
     * mailbox 466180170@qq.com
     */
    public function getFreeCommonMessageSend(string $openid, string $template_id, string $page, array $data)
    {
        return $this->miniAppService->sendSubscriptionMessage($openid, $template_id, $page, $data);
    }

    /**
     * 业务场景延时修改免单状态
     * @param string $orderNo
     * @param int $count
     * @return array|mixed
     */
    public function updateCommonFreeOrderStatus(string $orderNo,int $count){
        $order = OrderModel::query()
            ->from('store_order as order')
            ->leftJoin('store_activity as act', 'order.activity_id', '=', 'act.activityID')
            ->where(['order.order_no' => $orderNo])
            ->first(['order.order_no','order.activity_id','act.activity_prams']);
        $activity_prams = json_decode($order['activity_prams'],true);
        if($count==1){
            $delay = $activity_prams['first_invite_time'] * 3600;
            $is_second = $activity_prams['is_second'];
            $second_activation = $activity_prams['second_activation'];
            if((int)$is_second == 0){
                $data = ['type' => 1, 'order_no' => $orderNo];
                $this->container->get(DriverFactory::class)->get('free')->push(new FreeOrderJob($data), $delay);
            }else{
                $data = ['type' => 2, 'order_no' => $orderNo,'second_activation'=>$second_activation];
                $this->container->get(DriverFactory::class)->get('free')->push(new FreeOrderJob($data), $delay);
            }

        }else{
            $delay = $activity_prams['second_invite_time'] * 3600;
            $data = ['type' => 1, 'order_no' => $orderNo];
            $this->container->get(DriverFactory::class)->get('free')->push(new FreeOrderJob($data), $delay);
        }
    }

    /**
     * 业务场景二次激活时间段内状态
     * @param string $orderNo
     * @param string $second_activation
     */
    public function freeActivationCommonStatus(string $orderNo,string $second_activation){
            $data = ['type' => 3, 'order_no' => $orderNo];
            $delay = $second_activation * 3600;
            $this->container->get(DriverFactory::class)->get('free')->push(new FreeOrderJob($data), $delay);
    }
}